package com.wpf.system.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wpf.system.common.utils.MakeTree;
import com.wpf.system.entity.*;
import com.wpf.system.entity.vo.RoleMenuVO;
import com.wpf.system.mapper.MenuMapper;
import com.wpf.system.service.RoleMenuService;
import com.wpf.system.service.RoleService;
import com.wpf.system.mapper.RoleMapper;
import com.wpf.system.service.UserRoleService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
* @author ferna
* @description 针对表【role(用户角色表)】的数据库操作Service实现
* @createDate 2022-12-15 22:23:41
*/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService{

    @Resource
    private MenuMapper menuMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private RoleMenuService roleMenuService;

    @Value("${system.rootDefaultRole}")
    private Long rootDefaultRole;

    @Override
    public IPage<Role> getRoleList(int page, int pageSize, String searchContent) {
        if (StrUtil.isNotBlank(searchContent)) {
            return this.baseMapper.selectPage(new Page<>(page, pageSize),
                    Wrappers.<Role>lambdaQuery().like(Role::getRoleName,searchContent));
        }else {
            return this.baseMapper.selectPage(new Page<>(page, pageSize),null);
        }
    }

    @Override
    public int editRoleStatusById(Long id) { return this.baseMapper.editRoleStatusById(id); }

    @Override
    public RoleMenuVO getRoleMenuListByRid(Long uid, Long rid) {
        //查询用户是否具有管理员角色身份
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserRole::getUid,uid);
        queryWrapper.lambda().eq(UserRole::getRid,rootDefaultRole);
        UserRole userRole = userRoleService.getBaseMapper().selectOne(queryWrapper);
        List<Menu> list;
        if(ObjectUtil.isNotNull(userRole)){
            //如果是，返回全部权限
            list = menuMapper.selectList(null);
        }else{
            //如果不是管理员，返回自身拥有的权限
            list = menuMapper.getUserMenuById(uid);
        }
        List<Menu> menuList = MakeTree.makeMenuTree(list,0L);
        List<Menu> roleMenuList =  menuMapper.getMenuByRid(rid);
        //找出已拥有的权限
        List<Long> ids  = new ArrayList<>();
        Optional.ofNullable(list).orElse(new ArrayList<>()).stream().filter(item -> item != null).forEach(item ->{
            Optional.ofNullable(roleMenuList).orElse(new ArrayList<>()).stream().filter(dom -> dom != null).forEach(dom->{
                if(item.getId().equals(dom.getId())){
                    ids.add(dom.getId());
                }
            });
        });
        RoleMenuVO roleMenuVO = new RoleMenuVO();
        roleMenuVO.setRoleMenuList(menuList);
        roleMenuVO.setCheckList(ids.toArray());
        return roleMenuVO;
    }

    @Override
    @Transactional
    public Boolean deleteRoleById(Long id) {
        try{
            if(Convert.toBool(baseMapper.deleteById(id))){
                roleMenuService.deleteRoleMenuByRid(id);
                userRoleService.deleteUserRoleByRid(id);
                return true;
            }else{
                return false;
            }
        }catch (RuntimeException e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    @Override
    public List<Role> getUserCanGiveRoleByUid(Long uid) {
        //查询用户是否具有管理员角色身份
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserRole::getUid,uid);
        queryWrapper.lambda().eq(UserRole::getRid,rootDefaultRole);
        UserRole userRole = userRoleService.getBaseMapper().selectOne(queryWrapper);
        List<Role> list;
        if(ObjectUtil.isNotNull(userRole)){
            //如果是，返回全部角色
            list = roleMapper.selectList(null);
        }else{
            //如果不是管理员，返回自身拥有的角色
            list = baseMapper.getUserRoleByUid(uid);
        }
        return list;
    }
}




